package com.maclogic.db;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.maclogic.utils.Stat;

public class DAO_tab_panier {
	
	private SQLiteDatabase _myDataBase;

	public DAO_tab_panier(Context pContext) {
		SQLiteIntit lsqlinit=new SQLiteIntit(pContext, Stat.DB_NAME,null,1);
		
		// ouvertude de la bd
		_myDataBase=lsqlinit.getWritableDatabase();
		
	}
	
	public void close ()
	{
		_myDataBase.close();
	}
	
	public Cursor selectAll(String pCond)
	{
		String lSQL="SELECT * FROM "+Stat.TABLE_NAMEPAN;
		
		//Cursor mCursor=_myDataBase.query(Stat.TABLE_NAME, new String[] {Stat.COL_ID,
		//Stat.COL_REF, Stat.COL_CONST, Stat.COL_PRIX, Stat.COL_CARAC},null, null, null, null, null);
		
		if(pCond!=null && !pCond.equals(""))
			lSQL+=" "+pCond;
		
		//System.out.println(lSQL);
		
		return _myDataBase.rawQuery(lSQL, null);
//		if (mCursor != null) {
//			   mCursor.moveToFirst();
//			  }
//		
//		return mCursor;
		
	}
	
	public Cursor selectLpan(int pid)
	{
		String lSQL="SELECT * FROM "+Stat.TABLE_NAMEPAN+ " WHERE "+Stat.COL_PID+"="+pid;
		
		System.out.println(lSQL);
		
		return _myDataBase.rawQuery(lSQL, null);
		
	}

	public void insert (Panier ppan) {
		
		ContentValues lValues=new ContentValues();
		 lValues.put(Stat.COL_PIDA,ppan.getIdart());
		 lValues.put(Stat.COL_PREF,ppan.getRef());
		 lValues.put(Stat.COL_PPRIX,ppan.getPrix());
		 lValues.put(Stat.COL_PQTE,ppan.getQuantity());
		 _myDataBase.insert(Stat.TABLE_NAMEPAN, null, lValues);
		 
	}
	
	public void supligne(int pid){
		System.out.println("Suppression id "+pid);
		_myDataBase.delete(Stat.TABLE_NAMEPAN, Stat.COL_PID+" = "+pid, null);
	}
	
	public void modifligne(int pqte, int pid){
		ContentValues lValues=new ContentValues();
		 lValues.put(Stat.COL_PQTE,pqte);
		 _myDataBase.update(Stat.TABLE_NAMEPAN,lValues, Stat.COL_PID+" = "+pid, null);
		
	}
	
	public void razpanier(){
		_myDataBase.delete(Stat.TABLE_NAMEPAN,null, null);
		_myDataBase.delete("sqlite_sequence",null, null);
	}
	
	public ArrayList<Panier> getListFromCursor(Cursor pCursor){

		ArrayList<Panier> lList=new ArrayList<Panier>();

		if(pCursor.getCount()!=0){

			pCursor.moveToFirst();

			while(!pCursor.isAfterLast()){


				int lID=pCursor.getInt(pCursor.getColumnIndex(Stat.COL_PID));
				int lPID=pCursor.getInt(pCursor.getColumnIndex(Stat.COL_PIDA));
				String lRef=pCursor.getString(pCursor.getColumnIndex(Stat.COL_PREF));
				double lPrix=pCursor.getDouble(pCursor.getColumnIndex(Stat.COL_PRIX));
				int lPQte=pCursor.getInt(pCursor.getColumnIndex(Stat.COL_PQTE));

				Panier lPanier=new Panier(lPID, lRef, lPrix, lPQte);

				lList.add(lPanier);

				pCursor.moveToNext();
			}
		}
		return lList;
	}
	

}
